#include "ms575_algbackleftcircle.h"
using namespace MeasurE575;

AlgBackLeftCircle::AlgBackLeftCircle(int i):AlgBase(i)
{
}

void AlgBackLeftCircle::operator()(cv::Mat &srcImg,
                                   int id,
                                   std::map<string, float> &measRes,
                                   int fixtureId)
{
    std::vector<cv::Point> resptVec;

    for(auto i=0;i<8;i++)
    {
        if(i==1||i==5){
            continue;
        }
        std::vector<int> tparas;
        for(auto j=0;j< m_dataAllVec[i].m_edgeParam.cols;j++)
        {
            tparas.push_back(m_dataAllVec[i].m_edgeParam.at<int>(i,j));
        }

        std::vector<cv::Rect> rangVec;
        TemplateMatch(srcImg,m_dataAllVec[i],rangVec);
        cv::Mat imgt=srcImg(rangVec[0]).clone();
        std::vector<cv::Point> contours;
        edgedetect obj;
        obj.NewCircleEdge(imgt,tparas,contours);
        ImageCoordinateTransformation(contours,rangVec);

        std::unique_lock<std::mutex> lock(*AlgBase::mtxptrVec[id]);
        while (!AlgBase::flagVec[id])
        {
            (*AlgBase::cvarptrVec[id]).wait(lock);
        }
        for(auto &elem:contours)
        {
            cv::Point2f ptsIn(static_cast<float>(elem.x),static_cast<float>(elem.y)),ptsOut;
            CoordinateTransformationRelateToDot(datumBackVec[id],ptsIn,ptsOut);
            resptVec.push_back(ptsOut);
        }
    }

    std::string prefix = m_xmlFileNamePre + to_string(fixtureId) + "_";
    edgedetect obj;
    vector<float> cirres=obj.FitCircle(resptVec);
    measRes.insert(std::make_pair(string("FAI35-L-X-distance_pixel"), -cirres[1]));
    float fai35lx = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI35-L-X-distance")], -cirres[1]);
    measRes.insert(std::make_pair(string("FAI35-L-X-distance_real"), fai35lx));

    measRes.insert(std::make_pair(string("FAI35-L-Y-distance_pixel"), -cirres[0]));
    float fai35ly = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI35-L-Y-distance")], -cirres[0]);
    measRes.insert(std::make_pair(string("FAI35-L-Y-distance_real"), fai35ly));


    CalcPosition("FAI35-L-X-distance", "FAI35-L-Y-distance", "FAI35-L-position", prefix,
                 obj, m_standardValMap["FAI35-L-X-distance"], m_standardValMap["FAI35-L-Y-distance"],
                 -cirres[1], -cirres[0], measRes);

    measRes.insert(std::make_pair(string("FAI34-L-diam_pixel"), cirres[2]*2));
    float fai34ld = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI34-L-diam")], cirres[2]*2);
    measRes.insert(std::make_pair(string("FAI34-L-diam_real"), fai34ld));

    float fai48=obj.GetRoundness(resptVec,cv::Point2f(cirres[0],cirres[1]));
    measRes.insert(std::make_pair(string("FAI48-L-roundness_pixel"), fai48));
    float fai48lr = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI48-L-roundness")], fai48);
    measRes.insert(std::make_pair(string("FAI48-L-roundness_real"), fai48lr));
}
